import * as api from '@/services/idcApiEvent';
import { DrawerForm, ProFormInstance } from '@ant-design/pro-form';
import { Checkbox, Col, Divider, Row, TreeSelect, message } from 'antd';
import React, { useRef, useState } from 'react';
import * as c from '@/services/consts';
import { ProFormDependency, ProFormSelect, ProFormSwitch, ProFormText, ProFormTextArea } from '@ant-design/pro-components';
import { useModel } from 'umi';

type VpnServerFormProps = {
  visible: boolean;
  groupIds: string[] | undefined;
  serverIds: string[] | undefined;
  instIds: number[] | undefined;
  name: string | undefined;
  onCancel: () => void;
  onSubmit: () => void;
};

const VpnServerForm: React.FC<VpnServerFormProps> = (props) => {
  const { visible, groupIds, instIds, name, onCancel, onSubmit } =
    props;

  if (!visible) {
    return null;
  }

  
  const { getVpnGroupExTrees, suppliers } = useModel('useGlobalModel', (model) => ({
    getVpnGroupExTrees: model.getVpnGroupExTrees,
    suppliers: model.suppliers,
  }));

  // console.log(groupIds, groups, instIds, servers);

  // const [myloading, setMyloading] = useState<boolean>(true);
  // const [dataSource, setDataSource] = useState<API.CheckTask | undefined>(undefined,);
  // const [dataCheckers, setDataCheckers] = useState<API.CheckServer[] | undefined>(undefined);
  // const [dataTemplets, setDataTemplets] = useState<API.NodeTemplate[] | undefined>(undefined);
  // const [checkedList, setCheckedList] = useState<any[]>([]);
  // const [checkeBlock, setCheckeBlock] = useState<boolean>(false);
  // const [checkJob, setCheckJob] = useState<string|undefined>('checknode');
  // const [groupEditableKeys, setGroupEditableKeys] = useState<React.Key[]>(() =>groupIds?.map((item) => item),);
  // const [serverEditableKeys, setServerEditableKeys] = useState<React.Key[]>(() => instIds?.map((item) => item),);
  // const [changeCheckedList, setChangeCheckedList] = useState<any[]>([]);
  // const [checkedTempletList, setCheckedTempletList] = useState<any[]>([]);

  const formRef = useRef<ProFormInstance>();
  // const editorFormRef = useRef<EditableFormInstance<API.VpnServerNet>>();

  
  const [selGroupIds, setSelGroupIds] = useState<string[] | undefined>(undefined);
  // const [selSupplierIds, setSelSupplierIds] = useState<number[] | undefined>(undefined);

  // const loadData = async () => {
  //   let resultTemplet = await apiTemplate.all(undefined, undefined, undefined);
  //   if(resultTemplet && resultTemplet.success){
  //     setDataTemplets(resultTemplet.data);
  //   }

  //   setMyloading(false);
  // };

  // useEffect(() => {
  //   loadData();
  // }, []);

  const handleFormSubmit = async (record: API.IdcApiEventForm) => {    
    record.serverIps = formRef.current?.getFieldValue('ips');
    record.instanceIds = formRef.current?.getFieldValue('ids');
    record.groupIds = selGroupIds;

    const result = await api.add(record);
    if (result && result.success) {
      onSubmit();
    }
  };
  

  
  // const getActionSuppliers = (action: number) => {
  //   let options = [];
  //   for(let d of suppliers){
  //     if(d.configs?.changeIpActionCode && action == c.IdcApiEventAction.ChangeIp.value){
  //       options.push({label:d.name, value: d.id});
  //     }
  //   }

  //   return options;
  // };


  return (
    <DrawerForm<API.IdcApiEventForm>
      open={visible}
      title='服务器操作'
      formRef={formRef}
      autoFocusFirstInput
      width={1224}
      onFinish={handleFormSubmit}
      drawerProps={{
        // forceRender: true,
        // destroyOnClose: true,
        // closable: false,
        onClose: onCancel,
        maskClosable: false,
      }}
      // submitter={{
      //   render: (props, defaultDoms) => {
      //     return [defaultDoms[0]];
      //   },
      // }}
      // loading={myloading}
    >
      <Row gutter={24} style={{marginTop:10}}>
        <Col span={4}>
          <ProFormSelect
            name='action'
            label="操作动作"
            allowClear={false}
            options={c.IdcApiEventActionOptions}
            mode='single'
            rules={[{ required: true, message: '请选择操作动作' }]}
            fieldProps={{
              listHeight:600
            }}
          />
        </Col>
        <Col span={4}>
          <ProFormSwitch
            name='disableCheckIpBlacklist'
            label="禁止比对IP黑名单"
            initialValue={false}
          />
        </Col>
        {/* <ProFormDependency name={['action']}>
          {({ action }) => {
            if (action) {
              return (
              <Col span={4}>
                <ProFormSelect
                  name='supplierId'
                  label="服务商"
                  allowClear={false}
                  options={getActionSuppliers(action)}
                  mode='single'
                  rules={[{ required: true, message: '请选择服务商' }]}
                  fieldProps={{
                    listHeight:600
                  }}
                />
              </Col>
              );
            }
            return null;
          }}
        </ProFormDependency> */}
        {/* <Col span={4}>
          <ProFormSelect
            name='code'
            label="类型"
            allowClear={false}
            options={c.IdcApiEventTypeOptions}
            mode='single'
            rules={[{ required: true, message: '请选择类型' }]}
          />
        </Col> */}
        {/* <Col span={4}>
          <ProFormSelect
            name='job'
            label="检测类型"
            allowClear={false}
            options={c.CheckJobOptions}
            mode='single'
            initialValue={c.CheckJob.CheckNode.value}
            fieldProps={{
              listHeight:600
            }}
          />
        </Col>
        <ProFormDependency name={['job']}>
          {({ job }) => {
            if (job == c.CheckJob.CheckNode.value) {
              return (
              <Col span={4}>
                <ProFormSelect
                  name='mode'
                  label="检测模式"
                  allowClear={false}
                  options={c.CheckModeOptions}
                  mode='single'
                  initialValue={c.CheckMode.Simple.value}
                  fieldProps={{
                    listHeight:600
                  }}
                />
              </Col>
              );
            }
            return null;
          }}
        </ProFormDependency>
        <Col span={3} style={{paddingTop:35}}>
          <Checkbox
            checked={checkeBlock}
            onChange={(e) => {
              setCheckeBlock(e.target.checked);
            }}
          >
            检测被墙
          </Checkbox>
        </Col> */}
        <Col span={3} style={{paddingTop:35}}>
        </Col>
      </Row>

      
      <Row>
        <Col span={24} style={{marginBottom:-20}}>
          <ProFormText
            name="name"
            label="自定义名称"
            initialValue={name}
          />
        </Col>
      </Row>

      
      <Divider orientation="left" orientationMargin={0} style={{marginTop:20}}>分组</Divider>
      <Row gutter={24}>
        <Col span={24}>
          <TreeSelect
            style={{ minWidth: '100%', marginTop: 0, marginBottom: 30 }}
            listHeight={600}
            // maxTagCount={1}
            // dropdownMatchSelectWidth={false}
            // multiple={false}
            placeholder="选择分组过滤"
            allowClear={true}
            showSearch={true}
            treeCheckable={true}
            treeDefaultExpandAll
            treeData={getVpnGroupExTrees(undefined, true)}
            value={groupIds}
            treeNodeFilterProp="title"
            onChange={(value) => {
              setSelGroupIds(value ? value : undefined);
            }}
          />
        </Col>
      </Row>
      
      {/* <Divider orientation="left" orientationMargin={0}>服务商</Divider>
      <Row gutter={24}>
        <Col span={24}>
          <ProFormSelect
            name="supplierIds"
            label="服务器供应商"
            placeholder="请选择服务器供应商"
            allowClear={true}
            options={supplierOptions}
            mode='multiple'
            fieldProps={{
              showArrow: true,
              showSearch: true,
              listHeight: 600,
              // onChange: (value, option) => {
              //   setSelSupplierIds(value);
              // },
            }}
          />
        </Col>
      </Row> */}
      
      <Divider orientation="left" orientationMargin={0}>服务器</Divider>
      <Row gutter={24}>
        <Col span={12}>
          <ProFormTextArea
            name="ids"
            label='实例ID'
            fieldProps={{ rows: 25 }}
            initialValue={instIds?.join('\r\n')}
          />
        </Col>
        <Col span={12}>
          <ProFormTextArea
            name="ips"
            label='实例IP'
            fieldProps={{ rows: 25 }}
          />
        </Col>
      </Row>
       




    </DrawerForm>
  );
};

export default VpnServerForm;
